package cn.yunhe;

import cn.yunhe.model.Role;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;

/**
 * Created by zs on 2017/11/30.
 * 存取对象类型，并保证在同一个连接内
 */
public class Demo2 {

    @Test
    public void test1() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        RedisTemplate redisTemplate = ac.getBean(RedisTemplate.class);
        final Role role = new Role();
        role.setId(1L);
        role.setRoleName("jack");
        role.setNote("note_1");

        //同一个连接池的同一个Redis连接进行操作  匿名类方式
        SessionCallback callback = new SessionCallback<Role>() {
            public Role execute(RedisOperations ops) throws DataAccessException {
                ops.boundValueOps("role_1").set(role);
                return (Role) ops.boundValueOps("role_1").get();
            }
        };

        Role saveRole = (Role) redisTemplate.execute(callback);
        System.out.println(saveRole.getRoleName());

    }

}
